﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NHibernate;
using NHibernate.Linq;
using dbPoll_Application.Helpers;

namespace dbPoll_Application.Models
{
    public static class ResponseRepository
    {
        public static OptionResponse GetOptionResponseByDeviceID(ICollection<OptionResponse> responses, String deviceID)
        {
            var response = (from item in responses
                            where item.participant.deviceID == deviceID
                            select item).FirstOrDefault<OptionResponse>();
            return response;
        }

        public static int GetOptionResponseCountByDeviceIDAndQuestion(String deviceID, MultipleChoiceQuestion question)
        {
            var responses = new List<OptionResponse>();
            foreach (var option in question.options)
            {
                responses.AddRange(option.responses.Where(m => m.participant.deviceID == deviceID));
            }
            return responses.Count();
        }

        public static ShortResponse GetShortResponseByDeviceID(ICollection<ShortResponse> responses, String deviceID)
        {
            var response = (from item in responses
                            where item.participant.deviceID == deviceID
                            select item).FirstOrDefault<ShortResponse>();
            return response;
        }

        public static String[] GetNextGridResponses(int pollID)
        {
            var poll = PollRepository.GetPollByID(pollID);
            var keypads = from item in poll.gridResponses
                          select item.DeviceID;
            var responses = new List<String>();
            responses.AddRange(keypads);
            poll.gridResponses = null;
            PollRepository.UpdatePoll(poll);

            return responses.ToArray<String>();
        }
        public static QuestionOption GetOptionByResponse(int responseID, int questionID)
        {
            IList<QuestionOption> options = QuestionRepository.GetQuestionByID<MultipleChoiceQuestion>(questionID).options;
            return (from item in options where item.responses.Any(r => r.responseID == responseID) select item).FirstOrDefault();
        }
    }
}
